$(function() {  
    FastClick.attach(document.body);  
});
var colorO = '';
var chicun = '';
var val3 =0;
var val2 = 0;
var ind = 0;
$('.fImg').click(function() {
	ind = $(this).attr("statusIndex");
	
	$(this).parents(".shoppingcartDetail").find(".scnImg").show();
	$(this).parents(".shoppingcartDetail").find(".jia").show();
	$(this).parents(".shoppingcartDetail").find(".shoppingcartN input[type=text]").css({"margin-left":"0.5rem","border-left": "1px solid #ccc","border-right": "1px solid #ccc"}).attr("readonly", false);

	//alert(index);
	$(this).parents(".shoppingcartDetail").find('.jsb p').css({
		display: 'block'
	});
	$(this).parents(".shoppingcartDetail").find('.fImg').css({
		display: 'none'
	});
	//if($(this).parent().siblings(".sdwordC").find("span").text() != "暂无规格"){
	$(this).parents(".shoppingcartDetail").find('.sdWordC img').css({
		display: 'block'
	});
	//}
	$(this).parents(".shoppingcartDetail").find('.sdWordC ').css({
		background: 'rgb(238,238,238)'
	});
	//单个商品编辑完成
	$('.jsb p a:nth-child(2)').click(function() {
		$(this).parents(".shoppingcartDetail").find(".scnImg").hide();
		$(this).parents(".shoppingcartDetail").find(".jia").hide();
		$(this).parents(".shoppingcartDetail").find(".shoppingcartN input[type=text]").css({"margin-left":"3.5rem","border-left": "0px solid #ccc","border-right": "0px solid #ccc"}).attr("readonly",true);

		$(this).parents(".shoppingcartDetail").find('.jsb p').css({
			display: 'none'
		});
		$(this).parents(".shoppingcartDetail").find('.fImg').css({
			display: 'block'
		});
		$(this).parents(".shoppingcartDetail").find('.sdWordC img').css({
			display: 'none'
		});
		$(this).parents(".shoppingcartDetail").find('.sdWordC ').css({
			background: 'rgb(255,255,255)'
		});
        var goods_sku_info ="";
        var id = $(this).attr("id");
        var goods_sku_id = "";
        if($(this).parents(".shoppingcartDetail").find('.sdWordC ').attr("goodsSkuId")){
        	goods_sku_id =$('.sdWordC ').eq(ind).attr("goodsSkuId");
        }
		//修改商品规格与数量
        var length = $(this).parents(".shoppingcartDetail").find(".sdWordC").find("span").length - 1;
        $(this).parents(".shoppingcartDetail").find(".sdWordC").find("span").each(function(i,item){
			var skuInfo =  $(this).text().replace(/\s*\r?\n\s*/g, "").replace("已选中","");//去掉回车键；去掉空格；去掉空格；去掉已选中
			if($(this).text() !== "暂无规格"){
				if(length == i){
					goods_sku_info += skuInfo ;	
				}else{
					goods_sku_info += skuInfo + ",";
				}					
			}
		});
		var quantity = $(this).parents(".shoppingcartDetail").find(".shu").val();
		updateCartProductNoReload(id, quantity,goods_sku_id,goods_sku_info);
	});
	

});
/*$('.jsb p a:nth-child(1)').click(function() {
		for (var i=0;i<$('.jsb p a:nth-child(1)').length;i++) {
			index = $('.jsb p a:nth-child(1)').index(this);
		}
		deleteProduct($(this));
		if(($('.shoppingcartDetail').eq(index).siblings().length == 1)) {
			$('.shoppingcart_goods').eq(index).remove();
		} else {
			$('.shoppingcartDetail').eq(index).remove();
		}

});*/
function showJiaJian(){
	$(".scnImg").show();
	$(".jia").show();
	$(".shoppingcartN input[type=text]").css({"margin-left":"0.5rem","border-left": "1px solid #ccc","border-right": "1px solid #ccc"}).attr("readonly", false);
}
function hideJiaJian(){
	$(".scnImg").hide();
	$(".jia").hide();
	$(".shoppingcartN input[type=text]").css({"margin-left":"3.5rem","border-left": "0px solid #ccc","border-right": "0px solid #ccc"}).attr("readonly",true);
}

//点击上方编辑
var textC ='';
//购物车编辑完成
$('.jilu').click(function() {
	 textC= $(this).text();
	if(textC == '编辑') {
		showJiaJian();
		$(this).text('完成');
		$('.fImg').css({
			display: 'none'
		});
		$('.sdWordC img').css({
			display: 'block'
		});
		$('.jsb p').css({
			display: 'none'
		});
		$('.sdWordC').css({
			background: 'rgb(238,238,238)'
		});
		$('.jie').css({
			display: 'none'
		});
		$('.editor').css({
			display: 'block'
		});
	} else {//点击完成按钮
		hideJiaJian();
		$(this).text('编辑');
		$('.fImg').css({
			display: 'block'
		});
		$('.sdWordC img').css({
			display: 'none'
		});
		$('.sdWordC').css({
			background: 'rgb(255,255,255)'
		});
		$('.jsb p').css({
			display: 'none'
		});
	
		$('.jie').css({
			display: 'block'
		});
		$('.editor').css({
			display: 'none'
		});
		$(".shoppingcartDetail").each(function(){
	        var goods_sku_info ="";
	        var cartId = $(this).find(".sdImg").attr("cartId");
	        var goods_sku_id = $(this).find(".sdWordC").attr("goodsSkuId");
	        var length = $(this).find(".sdWordC").find("span").length - 1;
			$(this).find(".sdWordC").find("span").each(function(i,item){
				var skuInfo =  $(this).text().replace(/\s*\r?\n\s*/g, "").replace("已选中","");//去掉回车键；去掉空格；去掉空格；去掉已选中
				if($(this).text() !== "暂无规格"){
					if(length == i){
						goods_sku_info += skuInfo ;	
					}else{
						goods_sku_info += skuInfo + ",";
					}					
				}
			});
			var quantity = $(this).find(".shoppingcartN input[type=text]").val();
			//修改商品规格与数量
	        updateCartProduct(cartId, quantity,goods_sku_id,goods_sku_info);
			
		});
	}

});

//购物车
TotalNumber();
//数量减
$(".scnImg").click(function() {
    var t = $(this).parent().find('.shu');
    t.val(parseInt(t.val()) - 1);
    if (t.val() <= 1) {
      t.val(1);
    }
    TotalPrice();
    TotalNumber();
});
  // 数量加
$(".jia").click(function() {
    var t = $(this).parent().find('.shu');
    t.val(parseInt(t.val()) + 1);
    if (t.val() <= 1) {
      t.val(1);
    }
    TotalPrice();
    TotalNumber();
});
  // 点击商品按钮
$(".shoppingcartDetail .check").click(function() {
	for (var i=0;i<$(".check").length;i++) {
		index=$(".check").index(this);
	}
	if($(this).prop('checked')==true){
		$(this).parent().find('.image').attr('src',rootPath + '/image/yuan2.png');
	/*	$('.editor a').click(function(){
			$('.shoppingcartDetail').eq(index).css({display:'none'});
		});		*/
	}else{
		$('.editor a').click(function(){
			$('.shoppingcartDetail').eq(index).css({display:'block'});//			
		});
		$(this).parent().find('.image').attr('src',rootPath + '/image/yuan1.png')
	}
    var goods = $(this).closest(".shoppingcart_goods").find(".check"); //获取本店铺的所有商品
    var goodsC = $(this).closest(".shoppingcart_goods").find(".check:checked"); //获取本店铺所有被选中的商品
    var Shops = $(this).closest(".shoppingcart_goods").find(".checkBox"); //获取本店铺的全选按钮
    var Imgs = $(this).closest(".shoppingcart_goods").find(".images"); 
    var shopping =$(this).closest(".shoppingcart_goods");
    if(goods.length == goodsC.length) { //如果选中的商品等于所有商品
	      Shops.prop('checked', true); //店铺全选按钮被选中
	      Imgs.attr('src',rootPath + '/image/yuan2.png');
	     /* $('.editor a').click(function(){
				shopping.css({display:'none'});
		  });      */
	      if($(".checkBox").length == $(".checkBox:checked").length) { //如果店铺被选中的数量等于所有店铺的数量
	         $(".check_all").prop('checked', true);//全选按钮被选中
	         $(".check_all").parent().find('.image').attr('src',rootPath + '/image/yuan2.png');
	         TotalPrice();
	       /*  $('.editor a').click(function(){
				$('.shoppingcart').css({display:'none'});
				$('.editor').css({display:'none'});
				$('.jiesuan').css({display:'none'});
			 });*/
	      }else {
	      	$(".check_all").parent().find('.image').attr('src',rootPath + '/image/yuan1.png');
	        $(".check_all").prop('checked', false); //else全选按钮不被选中 
	         $('.jiesuan .image').attr('src',rootPath + '/image/yuan1.png');
	        TotalPrice();
	        $('.editor a').click(function(){
				$('.shoppingcart').css({display:'block'});
				$('.editor').css({display:'block'});
				$('.jiesuan').css({display:'block'});
			});
	      }
     }else { //如果选中的商品不等于所有商品
	      Shops.prop('checked', false); //店铺全选按钮不被选中
	      $('.editor a').click(function(){
			 shopping.css({display:'block'});
			 $('.shoppingcart').css({display:'block'});
			 $('.editor').css({display:'block'});	
		  });
	      Imgs.attr('src',rootPath + '/image/yuan1.png');
	      $(".check_all").parent().find('.image').attr('src',rootPath + '/image/yuan1.png');
	      $(".check_all").prop('checked', false); //全选按钮也不被选中
          $('.jiesuan .image').attr('src',rootPath + '/image/yuan1.png');
	      // 计算
	      TotalPrice();      
    }
  
});
//更新购物车结算数量
function updateCartNum(){
	   var checkNum=0;
	    $(".check:checked").each(function(){
			var quantity = $(this).parents(".shoppingcartDetail").find(".shu").val();
			checkNum+=parseInt(quantity);
	    });
	    $(".tallMonut").text(checkNum);
}
 //选中一个商品
$(".check").change(function() {
	 updateCartNum();
});

  // 点击店铺按钮
$(".checkBox").change(function() {
	for (var j=0;j<$(".checkBox").length;j++) {
		index=$(".checkBox").index(this);
	}
    if ($(this).prop("checked") == true) { //如果店铺按钮被选中
    	$(this).parent().find('.images').attr('src',rootPath + '/image/yuan2.png')
    	$(this).parents(".shoppingcart_goods").find(".image").attr('src',rootPath + '/image/yuan2.png');
        $(this).parents(".shoppingcart_goods").find(".check").prop('checked', true); //店铺内的所有商品按钮也被选中
        debugger;
       /* //删除选中的商品
        $('.editor a').click(function(){
			$('.shoppingcart_goods').eq(index).css({display:'none'});
			
		});*/
        if ($(".checkBox").length == $(".checkBox:checked").length) { //如果店铺被选中的数量等于所有店铺的数量
	        $(".check_all").prop('checked', true); //全选按钮被选中
	        $('.jiesuan .image').attr('src',rootPath + '/image/yuan2.png');
	        TotalPrice();
	       /* $('.editor a').click(function(){
				$('.shoppingcart').css({display:'none'});
				$('.editor').css({display:'none'});
				$('.jiesuan').css({display:'none'});
			});*/
        } else {
      	    $('.editor a').click(function(){
				$('.shoppingcart').css({display:'block'});
				$('.shoppingcart').css({display:'block'});
				$('.editor').css({display:'block'});	
			});
            $(".check_all").prop('checked', false); //else全选按钮不被选中
            $('.jiesuan .image').attr('src',rootPath + '/image/yuan1.png');
            TotalPrice();
      }
    } else { //如果店铺按钮不被选中
    	$(this).parent().find('.images').attr('src',rootPath + '/image/yuan1.png')
        $(this).parents(".shoppingcart_goods").find(".image").attr('src',rootPath + '/image/yuan1.png')
        $(this).parents(".shoppingcart_goods").find(".check").prop('checked', false); //店铺内的所有商品也不被全选
        $(".check_all").prop('checked', false); //全选按钮也不被选中
        $('.jiesuan .image').attr('src',rootPath + '/image/yuan1.png');
        TotalPrice();
        $('.editor a').click(function(){
			$('.shoppingcart_goods').eq(index).css({display:'block'});
			$('.shoppingcart').css({display:'block'});
			$('.editor').css({display:'block'});	
		});
    }
    updateCartNum();
});
//// 点击全选按钮
$('.check_all').click(function(){
	if($(this).prop('checked')==true){
		$('.check').prop('checked',true);
		$('.checkBox').prop('checked',true);
		$('.image').attr('src',rootPath + '/image/yuan2.png');
		$('.images').attr('src',rootPath + '/image/yuan2.png');
		TotalPrice();
		$('.editor a').click(function(){
			$('.shoppingcart').css({display:'none'});
			$('.editor').css({display:'none'});
			$('.jiesuan').css({display:'none'});
		});
	}else{
		$('.check').prop('checked',false);
		$('.checkBox').prop('checked',false);
		$('.image').attr('src',rootPath + '/image/yuan1.png');
		$('.images').attr('src',rootPath + '/image/yuan1.png');
		TotalPrice();
		$('.editor a').click(function(){
			$('.shoppingcart').css({display:'block'});
			$('.editor').css({display:'block'});
		});
	}
	$(".checkBox").change(); //执行店铺全选的操作
});

//计算总价
function TotalPrice() {
    var allprice = 0; //总价
    $(".shoppingcart_goods").each(function() { //循环每个店铺
      var oprice = 0; //店铺总价
     
      $(this).find(".check").each(function() { //循环店铺里面的商品
        if ($(this).is(":checked")) { //如果该商品被选中
          var num = parseInt($(this).parents(".shoppingcartDetail").find(".shu").val()); //得到商品的数量
          var price = parseFloat($(this).parents(".shoppingcartDetail").find(".sdWordP i").text()); //得到商品的单价
          var total = price * num; //计算单个商品的总价
          oprice += total; //计算该店铺的总价
          
        }
        $(this).closest(".shoppingcart_goods").find(".ShopTotal").text(oprice.toFixed(2)); //显示被选中商品的店铺总价
      });
      var oneprice = parseFloat($(this).find(".ShopTotal").text()); //得到每个店铺的总价
      allprice += oneprice; //计算所有店铺的总价
    });
    $(".jiage").text(allprice.toFixed(2)); //输出全部总价
    

    updateCartNum();
}
//计算总价
function TotalNumber() {
    var allnum=0;//总的个数
    $(".shoppingcart_goods").each(function() { //循环每个店铺
      var onum = 0; //店铺个数
      $(this).find(".check").each(function() { //循环店铺里面的商品    
          var num = parseInt($(this).parents(".shoppingcartDetail").find(".shu").val()); //得到商品的数量
          onum +=num;
      });
      allnum+=onum;//计算所有店铺的总个数
    });
    $(".headerTwo i").text(parseInt(allnum)); //输出全部个数
}
$('.sdWordC').click(function(){
	ind = $(this).attr("statusIndex");
	if($(this).find("span").text() == "暂无规格"){
		return false;
	}
	if($(this).find('img').css('display')=='block'){
		if(!$('.attribute').eq(ind).hasClass('failure')){
			$('.attribute').eq(ind).css({display:'block'});
			$('.mengban').eq(ind).css({display:'block'});
			$('body').css({overflow:'hidden'});
		    $('html').css({overflow:'hidden'});
		    $('.editor').css({display:'block'});
		}
	    $('.addAs').click(function(){	
	    	var cartId = $(this).attr("id");
	    	var $goodsF = $(".addAttributes").eq(ind).find('.goodesF').find('a');
	    	var $goodesT =$(".addAttributes").eq(ind).find('.goodesT').find('a');
	    	$goodsF.each(function(){
	    		if($(this).find("i").text()=='已选中'){
	    			$goodsF = $(this);
	    		}
	    	});
	    	$goodesT.each(function(){
	    		if($(this).find("i").text()=='已选中'){
	    			$goodesT = $(this);
	    		}
	    	});
		    if($goodsF || $goodesT){
				$('.attribute').eq(ind).css({display:'none'});
				$('.mengban').eq(ind).css({display:'none'});
				$('body').css({overflow:'visible'});
		        $('html').css({overflow:'visible'});
		        $('.sdWordC').eq(ind).find("span").find("i").text(colorO);
		        $('.sdWordC').eq(ind).find("span").find("b").text(chicun);
		        var goodsSkuId =$goodesT.attr("id") +"," + $goodsF.attr("id") ;
		        var goodsSkuInfo =$goodesT.attr("name") +"," + $goodsF.attr("name") ;		        
		        $(this).attr("goodsSkuId",goodsSkuId+",");
		        var quantity = $(this).parent().siblings(".shoppingcartN").find(".shu").val();
		        updateCartProductNoReload(cartId, quantity,goodsSkuId,goodsSkuInfo);			
		      }else{
				$(this).parent().parent().find('.attribute').css({display:'block'});
				$(this).parent().parent().find('.mengban').css({display:'block'});
				$('body').css({overflow:'hidden'});
				$('html').css({overflow:'hidden'});
		     }
		
	  });
	    
	}else{
		$('.attribute').css({display:'none'});
		$('.mengban').css({display:'none'});
	    $('.editor').css({display:'none'});
	   
	}
	
});

$('.attributes img').click(function(){
	$('.attribute').css({display:'none'});
	$('.mengban').css({display:'none'});
	$('body').css({overflow:'visible'});
	$('html').css({overflow:'visible'});
});

//商品规格选择
$('.goodesT a').click(function(){
	for (var i = 0; i<$('.goodesT a').length;i++) {
		index = $('.goodesT a').index(this);
	}
	colorO = $(this).text();
	$('.goodesT a i').text('')
	$('.goodesT a').css({border:'1px solid rgb(102,102,102)',color:'rgb(51,51,51)'})
	$(this).css({border:'1px solid rgb(202,14,84)',color:'rgb(202,14,84)'})
		$('.goodesT a i').eq(index).text('已选中');
		$('.goodesT a i').eq(index).css({fontSize:'0.0000001rem',opacity:'0',position:'absolute',left:'0'});
});
$('.goodesF a').click(function(){
	chicun = $(this).text();
	$('.goodesF a i').text('')
	for (var i = 0; i<$('.goodesF a').length;i++) {
		index = $('.goodesF a').index(this);
	}
	$('.goodesF a').css({border:'1px solid rgb(102,102,102)',color:'rgb(51,51,51)'})
	$(this).css({border:'1px solid rgb(202,14,84)',color:'rgb(202,14,84)'});
	$('.goodesF a i').eq(index).text('已选中');
	$('.goodesF a i').eq(index).css({fontSize:'0.0000001rem',opacity:'0',position:'absolute',left:'0'});
});


//  点击数量加减输入框
$('.shu').focus(function(){
	$('footer').css({display:'none'});
	$('.jiesuan').css({display:'none'});
});
$('.shu').blur(function(){
	$('footer').css({display:'block'});
	if($('.jilu').text()=='编辑'){
		$('.jie').css({display:'block'});
	}else{
		$('.editor').css({display:'block'});
	}
	
});

//移入收藏夹
$(".editor span:nth-child(5) ").click(function(){
	var $checkedBtn = $('.shoppingcartDetail :checkbox[name=items]:checked');
	var ids ="";
	for(var i =0; i< $checkedBtn.length; i++){
		ids += $($checkedBtn[i]).val() + ",";
	}
	moveToFavorites(ids);
});
//删除选中的商品
$('.editor a').click(function(){
	var $checkedBtn = $('.shoppingcartDetail :checkbox[name=items]:checked');
	var ids ="";
	for(var i =0; i< $checkedBtn.length; i++){
		ids += $($checkedBtn[i]).val() + ",";
	}
	deleteAllProduct (ids);
});
//删除商品
$(".jsb .del").click(function(){
	deleteProduct($(this));
});
//清除失效宝贝
$(".editor span:nth-child(7) ").click(function(){
	clearShortStockInvalidPorduct();
});
//清除因商品库存不足而失效的商品
function clearShortStockInvalidPorduct(){
	if(confirm('确认要清空失效的宝贝吗？')){
		var url = rootPath + '/cart/clearShortStockInvalidPorduct';
		var result = CommnUtil.ajax(url, {
		}, "json");
		if (result.flag) {
			alert('清空成功');
			reloadShopCart();
			getTotal();
		}else if(result.sessionValid){
			 reLogin();
		} else {
			alert('清空失败');
			reloadShopCart();
			getTotal();
		}
	}else{
		return false;
	}
}
//将选中的商品移入收藏夹
function moveToFavorites(ids){
	if (ids == "") {
		alert("请选择要收藏的商品！");
		return;
	}
	var data ={};
	data["ids"] = ids;
	data["collectionType"] = "1";  //收藏类型 1：商品，2：店铺 

  if(confirm("确认移入收藏夹吗？")) {
		 var url = rootPath + '/cart/moveToFavorites';
			var result = CommnUtil.ajax(url, data, "json");
			if (result.resultSuccess) {
				alert('移入收藏夹成功');
				reloadShopCart();
				getTotal();
			}else if(result.sessionValid){
				 reLogin();
			} else {
				alert('移入收藏夹失败');
				reloadShopCart();
				getTotal();
			}
	}else{
		return false;
	}
  
}

//删除购物车商品
function deleteProduct(obj){
	var id = $(obj).attr("id");
	if(confirm('确认要删除该宝贝吗？')){
		var url = rootPath + '/cart/deleteProduct';
		var result = CommnUtil.ajax(url, {
			id : id
		}, "json");
		if (result.flag) {
			alert('删除成功');
			reloadShopCart();
			getTotal();
		}else {
			alert('删除失败');
			reloadShopCart();
			getTotal();
		}
	}
}
//删除勾选的购物车商品
function deleteAllProduct (ids){
	if (ids == "") {
		alert("请选择删除项！！");
		return;
	}
    if(confirm("确认要删除该宝贝吗？")) {
	   var url = rootPath + '/cart/deleteAllProduct';
		var result = CommnUtil.ajax(url, {
			ids : ids
		}, "json");
		if (result.flag) {
			alert('删除成功');
			reloadShopCart();
			getTotal();
		} else {
			alert('删除失败');
			reloadShopCart();
			getTotal();
		}  
   }else{
	   return false;
   }
}
//修改购物车信息局部刷新购物车
function updateCartProductNoReload(id, quantity,goods_sku_id,goods_sku_info){
	var url = rootPath + '/cart/updateCartProduct';
	var result = CommnUtil.ajax(url, {
		id : id,
		quantity:quantity,
		goods_sku_id:goods_sku_id,
		goods_sku_info:goods_sku_info
	}, "json");
	console.log(result);
	updateCartNum();
}
//修改购物车信息
function updateCartProduct(id, quantity,goods_sku_id,goods_sku_info){
	var url = rootPath + '/cart/updateCartProduct';
	var result = CommnUtil.ajax(url, {
		id : id,
		quantity:quantity,
		goods_sku_id:goods_sku_id,
		goods_sku_info:goods_sku_info
	}, "json");	
	reloadShopCart();
	console.log(result);
	updateCartNum();
}
//回到购物车列表页面
function reloadShopCart(){
	window.location.href=rootPath + '/cart/getCart';
}
//重新登录页面
function reLogin(){
	window.location.href=rootPath + '/member/loginPre?redirect=/cart/cartPage?cartType=all';
}


//结算
$(".tallyOrders").one("click",function(){
	var url = rootPath + "/order/tallyOrders";
	//var index = layer.load(5,{offset: ['50%', '50%']}); //进度条 遮罩
	//获取选中要结算的商品
	var $checkedBtn = $('.sdImg :checkbox[name=items]:checked');
	if(  $checkedBtn.length < 1){
		return false;
     }
	var ids ="";
	for(var i =0; i< $checkedBtn.length; i++){
		ids += $($checkedBtn[i]).val() + ",";
	}
	var result = CommnUtil.ajax(url,
			{ids:ids},
			"html");

	result = JSON.parse(result);
	if(result.resubmitFlag){
		 alert("宝贝已生成订单,请重新添加");	
		 reloadShopCart();
		 return;
	}
	if (result.flag) {
		if(CommnUtil.notNull(result.stockMessage)){ 
			 alert(result.stockMessage);	
	         Pause(this,6000);//调用暂停函数
		}else{ 
			var $url = rootPath + '/order/order';		
			window.open($url,'_self'); 
		}

		layer.close(index);
	}else if(result.sessionValid){
		 reLogin();
		 layer.close(index);
	} else {
		 alert('结算失败');	
         Pause(this,6000);//调用暂停函数
	     this.NextStep=function(){
			reloadShopCart();
			layer.close(index);
	     }
	}
	
});
